import React, { Component } from 'react';
import _ from 'lodash';
import Button from '../../../components/Button';
import user from "../../../common/models/user";

const DURING = 120;

export default class SendBtn extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sending: false,
      last: this.props.during || DURING,
      during: this.props.during || DURING
    };
  }
  interval = '';
  componentWillReceiveProps(next) {
    if (next.sendError) {
      this.setState({
        sending: false
      }, () => {
        user.setSendError(false);
        clearInterval(this.interval);
      })
    }
  }
  send = () => {
    const { sending } = this.state;
    const { sendAction, disabled } = this.props;
    if (sending || disabled) {
      return;
    }
    this.setState(
      {
        sending: true
      },
      () => {
        this.interval = setInterval(() => {
          const { last, during } = this.state;
          if (last > 1) {
            this.setState({
              last: last - 1
            });
          } else {
            this.setState(
              {
                last: during,
                sending: false
              },
              () => {
                clearInterval(this.interval);
              }
            );
          }
        }, 1000);
        if (_.isFunction(sendAction)) {
          sendAction();
        }
      }
    );
  };
  render() {
    const { sending, last } = this.state;
    const text = sending ? `${last}秒` : '发送';
    return (
      <Button
        onPress={this.send}
        style={this.props.style}
        disabled={sending || this.props.disabled}
        type="primary"
        size="small"
        title={text}
      />
    );
  }
}
